<?php
/*
 * 广告模块
 * @package    system
 * @author     Sameal
 * @copyright  Copyright (c) 2013 ixdcw team
 * @version    $Id: bbc2ed5badd10818735a745220ea482492464788 $
 */
defined('IN_IXDCW') or exit('Access Denied');
/**
 * Class AdModule
 */
class AdModule extends BasicModule{
	private  $_aid;
	private  $_pid;
	private  $_ppid;
	private  $_uid;
	private  $_table;
	private  $_table_place;
	private  $_table_city;
	private  $_table_price;
	private  $_table_user;

    function  __construct()  {
	    parent::__construct();
		$this->_table = $this->_db->pre.'ad';
		$this->_table_place = $this->_db->pre.'ad_place';
	    $this->_table_city = $this->_db->pre.'city';
	    $this->_table_price = $this->_db->pre.'ad_price';
	    $this->_table_user = $this->_db->pre.'ad_user';
	    $this->_table_type = $this->_db->pre.'type';
    }

	public function setAid($aid) {
		$this->_aid = $aid;
	}

	public function getAid() {
		return $this->_aid;
	}

	public function setPid($pid) {
		$this->_pid = $pid;
	}

	public function getPid() {
		return $this->_pid;
	}
	function isPlace($place) {
		global $L;
		if(!is_array($place)) return false;
		if(!$place['name']) return $this->err($L['pass_ad_name']);
		if($place['typeid'] == 3 || $place['typeid'] == 4 || $place['typeid'] == 5) {
			if(!$place['width']) return $this->err($L['pass_place_width']);
			if(!$place['height']) return $this->err($L['pass_place_height']);
		}
		if($place['typeid'] == 6 || $place['typeid'] == 7) {
			if(!$place['moduleid']) return $this->err($L['pass_place_module']);
			$condition = "moduleid=$place[moduleid] AND typeid=$place[typeid]";
			if($this->_pid) $condition .= " AND pid<>$this->_pid";
			$r = $this->_db->getOne("SELECT pid FROM {$this->_table_place} WHERE $condition");
			if($r) return $this->err($L['pass_place_repeat']);
		}
		return true;
	}

	function setPlace($place) {
		global $DT_TIME, $_username;
		if(!$this->_pid) $place['addtime'] = $DT_TIME;
		$place['edittime'] = $DT_TIME;
		$place['editor'] = $_username;
		$place['width'] = intval($place['width']);
		$place['height'] = intval($place['height']);
		$place['width'] = intval($place['width']);
		$place['height'] = intval($place['height']);
		$place['catid'] = intval($place['catid']);
		unset($place['username']);
		clear_upload($place['thumb']);
		return $place;
	}

	function addPlace($place) {
		$place = $this->setPlace($place);
		$sqlk = $sqlv = '';
		foreach($place as $k=>$v) {
			$sqlk .= ','.$k; $sqlv .= ",'$v'";
		}
        $sqlk = substr($sqlk, 1);
        $sqlv = substr($sqlv, 1);
		$this->_db->query("INSERT INTO {$this->_table_place} ($sqlk) VALUES ($sqlv)");
		$this->_pid = $this->_db->insertId();
		return $this->_pid;
	}
	
	function editPlace($place) {
		$place = $this->setPlace($place);
		$sql = '';
		foreach($place as $k=>$v) {
			$sql .= ",$k='$v'";
		}
        $sql = substr($sql, 1);
	    $this->_db->query("UPDATE {$this->_table_place} SET $sql WHERE pid=$this->_pid");
		return true;
	}
	function getAdResidueCity($payid){
		global $AREA;
		$allAd = $this->_db->getOne("SELECT * FROM {$this->_table_user} WHERE payid='$payid'");
		$existAd = $this->_db->getAll("SELECT * FROM {$this->_table} WHERE payid='$payid'");

		$areaids = explode(',',$allAd['areaids']);


		foreach($areaids as $areaid){
			if($areaid=='0'){
				$adResidueCity[0] = $AREA[3421];
				$adResidueCity[0]["areaname"] = '主站';
				$adResidueCity[0]["areaid"] = '0';
				$adResidueCity[0]['disabled']=1;
			}else{
				$adResidueCity[$areaid]=$AREA[$areaid];
				$adResidueCity[$areaid]['disabled']=1;
			}
		}

		foreach($existAd as $ad){
			if(in_array($ad['areaid'],$areaids)){
				$adResidueCity[$ad['areaid']]['disabled']=0;
			}
		}

		return $adResidueCity;
	}
	function getPlaceResidueCity($pid,$payid = 0){
		if($payid){
			$orders = $this->_db->getAll("SELECT * FROM {$this->_table_user} WHERE pid='$pid' AND payid <> '$payid'");
		}else{
			$orders = $this->_db->getAll("SELECT * FROM {$this->_table_user} WHERE pid='$pid'");
		}
		$hasCityId='';
		$hasStation = 0;
		foreach($orders as $orderValue){
			if($orderValue['areaids']=='0'){
				$hasStation = 1;
			}else{
				$hasCityId .= trim($orderValue['areaids'],',').',';
			}
		}
		$hasCityId = trim($hasCityId,',');

		if($hasCityId){
			$city_tem = $this->_db->getAll("SELECT * FROM {$this->_table_city} WHERE areaid NOT IN ({$hasCityId})");
		}else{
			$city_tem = $this->_db->getAll("SELECT * FROM {$this->_table_city}");
		}

		if(!$hasStation){
			$city_tem[] = array("areaid"=> "0","name"=>"主站","style"=>"","iparea"=>"","domain"=>"","letter"=> "q","listorder"=> "100","template"=> "index-city","seo_title"=>"","seo_keywords"=> "","seo_description"=> "");
		}

		foreach($city_tem as $value){
			$city[$value['areaid']] = $value;
		}

		return $city;
	}
	function getOnePlace() {
        return $this->_db->getOne("SELECT * FROM {$this->_table_place} WHERE pid='$this->_pid'");
	}
	function  getUsers($pid) {
		return $this->_db->getAll("SELECT * FROM {$this->_table_user} WHERE pid='$pid'");
	}
	function  getUserById($id) {
		return $this->_db->getOne("SELECT * FROM {$this->_table_user} WHERE payid='$id'");
	}
	function  getTypeName($typeid) {
		return $this->_db->getVar("SELECT typename FROM {$this->_table_type} WHERE typeid='$typeid'");
	}
	function getSubnationPrice() {
		//查找$pid 信息
		$adPlace = $this->_db->getOne("SELECT * FROM {$this->_table_place} WHERE pid='$this->_pid'");

		//查找分站列表
		$city = $this->_db->getAll("SELECT * FROM {$this->_table_city}");

		//查找分站价格列表
		$price_tem = $this->_db->getAll("SELECT * FROM {$this->_table_price} WHERE pid='$this->_pid'");
		$price=array();
		//转换格式
		foreach($price_tem as $value){
			$price[$value['areaid']] = $value['price'];
		}

		//对比city与price建立array
		$subnationPrice=array();
		foreach($city as $cityInfo){
			if($price[$cityInfo['areaid']]){
				$subnationPrice[$cityInfo['areaid']]=$price[$cityInfo['areaid']];
			}else{
				$subnationPrice[$cityInfo['areaid']]=$adPlace['subnation_price'];
			}
		}
		return $subnationPrice;
	}
	function getListPlace($condition = '1', $order = 'listorder DESC,pid DESC') {
		global $MOD, $TYPE, $items,$cache;
		$num = $this->_db->count($this->_table_place, $condition, $cache);
		$items=$num;
		$this->_pn->recordsPerPage($this->_pagesize);
		$this->_pn->records($num);
		$sql = "SELECT * FROM {$this->_table_place}";
		$sql .= $condition ? " WHERE {$condition}" : '';
		$sql .= $order ? " ORDER BY {$order}" : '';
		$sql .= " LIMIT " . ($this->_pn->getPage() - 1) * $this->_pagesize . ',' . $this->_pagesize;
		$ads = array();
		$result = $this->_db->query($sql);
		while($r = $this->_db->fetchArray($result)) {
			$r['name'] = set_style($r['name'], $r['style']);
			$r['adddate'] = timetodate($r['addtime'], 5);
			$r['editdate'] = timetodate($r['edittime'], 5);
			$r['width'] or $r['width'] = '--';
			$r['height'] or $r['height'] = '--';
			$r['typename'] = $TYPE[$r['typeid']];
			$r['typeurl'] = $MOD['ad_url'].rewrite('index.php?typeid='.$r['typeid']);
			$ads[] = $r;
		}
		return $ads;
	}

	function getPlace($condition = '1') {
		$ads = array();
		$result = $this->_db->query("SELECT placeT.*,typeT.typename FROM {$this->_table_place} placeT LEFT JOIN {$this->_table_type} typeT ON placeT.catid=typeT.typeid WHERE $condition ORDER BY listorder DESC,pid DESC");
		while($r = $this->_db->fetchArray($result)) {
			$r['adddate'] = timetodate($r['addtime'], 5);
			$r['editdate'] = timetodate($r['edittime'], 5);
			$r['width'] or $r['width'] = '--';
			$r['height'] or $r['height'] = '--';
			$ads[$r['pid']] = $r;
		}
		return $ads;
	}
	function getPlacePay($pid) {
		$pays = array();
		$result = $this->_db->query("SELECT * FROM {$this->_table_place_pay} where pid='$pid'");
		while($r = $this->_db->fetchArray($result)) {
			$ads[$r['pid']] = $r;
		}
		return $ads;
	}
	function update_replace($pid, $item = array()) {
		global $db;
		$item or $item = $this->_db->getOne("SELECT * FROM {$this->_table_place} WHERE pid=$pid");
		$type = PCache::read('type-ad_place.php');
		$webpage = $this->_db->getOne("SELECT * FROM {$db->getPre()}webpage WHERE title = '".$type[$item['catid']]['typename']."广告位' or title = '".$type[$item['catid']]['typename']."'");
		$item['itemid'] = $pid;
		$linkurl =$webpage ? url('extend/webpage', 'itemid='.$webpage['itemid']) : SITE_URL;
		$sql = "linkurl='$linkurl'";
		$this->_db->query(Sql::update($this->_table_place,"$sql","pid=$pid"));
	}

	function orderPlace($listorder) {
		if(!is_array($listorder)) return false;
		foreach($listorder as $k=>$v) {
			$k = intval($k);
			$v = intval($v);
			$this->_db->query("UPDATE {$this->_table_place} SET listorder=$v WHERE pid=$k");
		}
		return true;
	}

	function deletePlace($pid) {
		if(is_array($pid)) {
			foreach($pid as $v) {
				$this->deletePlace($v);
			}
		} else {
			$p = $this->_db->getOne("SELECT * FROM {$this->_table_place} WHERE pid=$pid");
			$this->_db->query("DELETE FROM {$this->_table_place} WHERE pid=$pid");
			$filename = $p['typeid'] > 5 ? 'ad_'.$p['moduleid'].'_d'.$p['typeid'].'.htm' : 'ad_'.$a['pid'].'_d0.htm';
			File::del(DT_CACHE.'/htm/'.$filename);
			File::del(DT_CACHE.'/htm/ad_'.$pid.'.htm');
			File::del(DT_ROOT.'/file/script/A'.$pid.'.js');
			$result = $this->_db->query("SELECT aid FROM {$this->_table} WHERE pid=$pid ORDER BY aid DESC");
			while($r = $this->_db->fetchArray($result)) {
				$this->delete($r['aid']);
			}
		}
	}

	function isAd($ad) {
		global $L , $AREA, $db;

		if(!is_array($ad)) return false;
		if(!$ad['areaids']) return $L['pass_cityid'];
		if(!$ad['title']) return $this->err($L['pass_ad_title']);
		if(!$ad['payid']){
			return $this->err($L['pass_ad_payid']);
		}
		if($ad['typeid'] == 1 || $ad['typeid'] == 7) {
			if(!$ad['code']) return $this->err($L['pass_ad_code']);
		} else if($ad['typeid'] == 2) {
			if(!$ad['text_name']) return $this->err($L['pass_ad_text_name']);
			if(!$ad['text_url']) return $this->err($L['pass_ad_text_url']);
		} else if($ad['typeid'] == 3) {
			if(!$ad['image_src']) return $this->err($L['pass_ad_image_src']);
		} else if($ad['typeid'] == 4) {
			if(!$ad['flash_src']) return $this->err($L['pass_ad_flash_src']);
		}

		foreach($ad['areaids'] as $keyarea => $areaid){
			if($this->_db->getAll("SELECT * FROM {$this->_table} WHERE payid={$ad['payid']} AND areaid=$areaid")){
				return $this->err($AREA[$areaid]['areaname'].$L['city_has_choose']);
			}
			if(!$this->_db->getAll("SELECT * FROM {$db->getPre()}city WHERE areaid=$keyarea") && $areaid != '0'){
				return $this->err($AREA[$areaid]['areaname'].$L['city_not_subnation']);
			}
		}

		return true;
	}

	function setAd($ad) {
		global $DT_TIME, $_username;
		if(!$this->_aid) $ad['addtime'] = $DT_TIME;
		$ad['edittime'] = $DT_TIME;
		$ad['editor'] = $_username;
		$ad['url'] = '';
		if($ad['typeid'] == 2) {
			$ad['url'] = $ad['text_url'];
		} else if($ad['typeid'] == 3 || $ad['typeid'] == 5) {
			$ad['url'] = $ad['image_url'];
		} else if($ad['typeid'] == 4) {
			$ad['url'] = $ad['flash_url'];
		}
		clear_upload($ad['image_src'].$ad['flash_src'].$ad['code']);
		return $ad;
	}
	function isPay($pay) {
		global $L , $AREA;
		if(!is_array($pay)) return false;

		if(!$pay["pid"]||!is_numeric($pay["pid"])) return $this->err($L['not_ad_place']);
		if(!$pay["username"]) return $this->err($L['spread_pass_username']);
		if(!$pay["starttime"]|| !is_date($pay["starttime"])) return $this->err($L['pass_ad_from']);
		if(!$pay["overtime"]|| !is_date($pay["overtime"])) return $this->err($L['pass_ad_end']);
		if(strtotime($pay['starttime'].' 0:0:0') > strtotime($pay['overtime'].' 23:59:59')) return $this->err($L['pass_ad_bad_date']);

		if(!$pay["areaids"]) return $this->err($L['pass_cityid']);
		//检测是否同时选择主站与分站
		if(in_array('0',$pay["areaids"]) && count($pay["areaids"])>1 && is_array($pay["areaids"])){
			return $this->err($L['not_subnation_and_nation']);
		}
		//检查此广告位订单地区是否已被其他人购买
		$hasAreaids = $this->getPlaceResidueCity($pay['pid'],$pay['payid']);
		foreach($pay["areaids"] as $areaid){
			if(!$hasAreaids[$areaid]){
				return $this->err($AREA[$areaid]['areaname'].$L['city_has_choose']);
			}
		}
		return true;
	}

	function setPay($pay) {
		global $DT_TIME, $_username;
		if(!$pay['payid']){
			unset($pay['payid']);
		}
		if($pay['username'] && get_user($pay['username'],'username','userid')){
			$pay['userid']=get_user($pay['username'],'username','userid');
		}else{
			$pay['userid']=0;
		}
		unset($pay['username']);
		$pay['starttime'] = strtotime($pay['starttime'].' 0:0:0');
		$pay['overtime'] = strtotime($pay['overtime'].' 23:59:59');
		$pay['areaids']=implode(',',$pay['areaids']);
		return $pay;
	}
	function addPay($pay) {
		$order = $this->setPay($pay);
		$sqlk = $sqlv = '';
		foreach($order as $k=>$v) {
			$sqlk .= ','.$k; $sqlv .= ",'$v'";
		}
		$sqlk = substr($sqlk, 1);
		$sqlv = substr($sqlv, 1);
		$this->_db->query("INSERT INTO {$this->_table_user} ($sqlk) VALUES ($sqlv)");
		$this->_uid = $this->_db->insertId();
		return $this->_uid;
	}
	function editPay($pay) {
		$order = $this->setPay($pay);
		$sqlk = $sqlv = '';
		foreach($order as $k=>$v) {
			$sqlk .= ','.$k; $sqlv .= ",'$v'";
		}
		$sqlk = substr($sqlk, 1);
		$sqlv = substr($sqlv, 1);
		$this->_db->query("DELETE FROM {$this->_table_user} WHERE payid=$order[payid]");
		$this->_db->query("INSERT INTO {$this->_table_user} ($sqlk) VALUES ($sqlv)");
		$this->_uid = $this->_db->insertId();
		return $this->_uid;
	}
	function delPay($payid) {
		$this->_db->query("DELETE FROM {$this->_table_user} WHERE payid=$payid");
		$this->_uid = $this->_db->insertId();
		return $this->_uid;
	}
	/**
	 * 判断地区价格是否符合
	 * @param array $subnationPrice 地区分站广告位价格列表
	 * @param int   $autoSubnationPrice   分站默认价格列表
	 * @return boolean 判断数据是否符合格式
	 */
	function isAsp($subnationPrice,$autoSubnationPrice){
		global $L;
		if(!is_array($subnationPrice)) return false;
		if(!autoSubnationPrice||$autoSubnationPrice==0) return $this->err($L['no_subnation_price']);

		foreach($subnationPrice as $value){
			if(!is_numeric($value)){
				return $this->err($L['price_must_int']);
			}
			if($value<=0){
				return $this->err($L['price_must_greater_that_0']);
			}
		}
		return true;
	}
	/**
	 * 地区广告价格设置
	 * @param array $subnationPrice 地区分站广告位价格列表
	 * @param int   $autoSubnationPrice   分站默认价格列表
	 * @return array
	 */
	function setAsp($subnationPrice,$autoSubnationPrice){
		global $AREA , $DT_TIME, $_username;
		//取出所有与默认分站价格不一样的特例地区价格
		foreach($subnationPrice as $areaid => $priceValue){
			if(intval($priceValue)==intval($autoSubnationPrice)){
				unset($subnationPrice[$areaid]);
			}
		}

		//读取已存在的所有特例价格
		$ad_place_price = $this->_db->getAll("SELECT * FROM {$this->_table_price} WHERE pid='$this->_pid'");
		//与表单价格对应 存在判断价格是否改动 不存在则删
		foreach($ad_place_price as $priceValue){
			if($subnationPrice[$priceValue['areaid']]){
				if(intval($subnationPrice[$priceValue['areaid']])!=intval($priceValue['price'])){
					$cost=$subnationPrice[$priceValue['areaid']];
					$cityid=$priceValue['areaid'];
					$this->_db->query("UPDATE {$this->_table_price} SET price=$cost WHERE pid='$this->_pid' and areaid='$cityid'");
				}
				unset($subnationPrice[$priceValue['areaid']]);
			}else{
				$cityid=$priceValue['areaid'];
				$this->_db->query("DELETE FROM {$this->_table_price} WHERE pid='$this->_pid' and areaid='$cityid'");
			}
		}
		//添加新的地区价格
		foreach($subnationPrice as $areaid => $priceValue){
			$this->_db->query("INSERT INTO {$this->_table_price} (pid,areaid,price) VALUES ('$this->_pid','$areaid','$priceValue')");
			$this->_ppid = $this->_db->insertId();
			unset($subnationPrice[$areaid]);
		}
		return $subnationPrice;
	}


	function getOne() {
        return $this->_db->getOne("SELECT * FROM {$this->_table} WHERE aid='$this->_aid'");
	}

	function getList($condition = '1', $order = 'fromtime DESC') {
		global $items, $DT_TIME, $L,$cache;
		$num = $this->_db->count($this->_table, $condition, $cache);
		$items=$num;
		$this->_pn->recordsPerPage($this->_pagesize);
		$this->_pn->records($num);
		$sql = "SELECT * FROM {$this->_table}";
		$sql .= $condition ? " WHERE {$condition}" : '';
		$sql .= $order ? " ORDER BY {$order}" : '';
		$sql .= " LIMIT " . ($this->_pn->getPage() - 1) * $this->_pagesize . ',' . $this->_pagesize;
		$ads = array();
		$result = $this->_db->query($sql);
		while($r = $this->_db->fetchArray($result)) {
			$r['adddate'] = timetodate($r['addtime'], 5);
			$r['editdate'] = timetodate($r['edittime'], 5);
			$u = $this->_db->getOne("SELECT * FROM {$this->_table_user} WHERE payid=$r[payid]");
			$r['fromdate'] = timetodate($u['starttime'], 3);
			$r['todate'] = timetodate($u['overtime'], 3);
			$r['username'] = get_user($u['userid'],'userid','username');
			$r['days'] = $u['overtime'] > $DT_TIME ? intval(($u['overtime']-$DT_TIME)/86400) : 0;
			if($u['overtime'] < $DT_TIME) {
				$r['process'] = $L['status_expired'];
			} else if($r['fromtime'] > $DT_TIME) {
				$r['process'] = $L['status_not_start'];
			} else {
				$r['process'] = $L['status_displaying'];
			}
			$ads[] = $r;
		}
		return $ads;
	}

	function add($ad) {
		$ad = $this->setAd($ad);
		$areaids=$ad['areaids'];
		unset($ad['areaids']);
		foreach($areaids as $areaid){
		$ad['areaid'] = $areaid;
		$sqlk = $sqlv = '';
		foreach($ad as $k=>$v) {
			$sqlk .= ','.$k; $sqlv .= ",'$v'";
		}
        $sqlk = substr($sqlk, 1);
        $sqlv = substr($sqlv, 1);
		$this->_db->query("INSERT INTO {$this->_table} ($sqlk) VALUES ($sqlv)");
		$this->_aid = $this->_db->insertId();
		$this->_db->query("UPDATE {$this->_table_place} SET ads=ads+1 WHERE pid='$ad[pid]'");
		}
		return $this->_aid;
	}

	function edit($ad) {
		$ad = $this->setAd($ad);
		$sql = '';
		foreach($ad as $k=>$v) {
			$sql .= ",$k='$v'";
		}
        $sql = substr($sql, 1);
		$sql = "UPDATE {$this->_table} SET $sql WHERE aid=$this->_aid";
		$this->_db->query($sql);
		return true;
	}

	function delete($aid) {
		if(is_array($aid)) {
			foreach($aid as $v) {
				$this->delete($v);
			}
		} else {
			$this->_aid = $aid;
			$a = $this->getOne();
			$filename = ad_name($a);
			File::del(DT_CACHE.'/htm/'.$filename);
			$userid = get_user($a['username']);
			if($a['image_src']) PictureUpload::deletePicture($a['image_src'], $userid);
			if($a['flash_src']) PictureUpload::deletePicture($a['flash_src'], $userid);
			$this->_db->query("DELETE FROM {$this->_table} WHERE aid=$aid");
			$this->_db->query("UPDATE {$this->_table_place} SET ads=ads-1 WHERE pid=$a[pid]");
		}
	}

	function orderAd($listorder) {
		if(!is_array($listorder)) return false;
		foreach($listorder as $k=>$v) {
			$k = intval($k);
			$v = intval($v);
			$this->_db->query("UPDATE {$this->_table} SET listorder=$v WHERE aid=$k");
		}
		return true;
	}
	function getAdByPidCityid($pid,$cityid){
		return $this->_db->getOne("SELECT * FROM {$this->_table} WHERE pid='$pid' and areaid='$cityid'");
	}
}
?>